<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="100px"
    :disabled="!!(disabled || attrs.oper)"
    v-loading="formLoading"
  >
    <el-row>
      <el-col :span="12">
        <el-form-item label="物资名称" prop="name">
          <el-input v-model="formData.name" :disabled="true" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="物资编号" prop="assetCode">
          <el-input v-model="formData.assetCode" :disabled="true" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="领用人" prop="userIds" v-if="oper == 'borrow'">
      <div class="flex flex-wrap gap-2">
        <div
          v-for="user in selectedUsers"
          :key="user.id"
          class="bg-gray-100 h-35px rounded-3xl flex items-center pr-8px dark:color-gray-600 position-relative"
        >
          <el-avatar class="!m-5px" :size="28" v-if="user.avatar" :src="user.avatar" />
          <el-avatar class="!m-5px" :size="28" v-else>
            {{ user.nickname.substring(0, 1) }}
          </el-avatar>
          {{ user.nickname }}
          <Icon
            icon="ep:close"
            class="ml-2 cursor-pointer hover:text-red-500"
            @click="handleRemoveUser(user)"
          />
        </div>
        <el-button type="primary" link @click="openUserSelect">
          <Icon icon="ep:plus" />选择人员
        </el-button>
      </div>
    </el-form-item>

    <el-form-item label="维修费（元）" prop="price" v-if="oper == 'reputin'">
      <el-input-number
        v-model="formData.price"
        :min="0"
        clearable
        controls-position="right"
        class="!w-1/1"
      />
    </el-form-item>

    <el-form-item
      label="备注"
      prop="inRemark"
      v-if="['borrow', 'returns', 'reputin'].includes(oper)"
    >
      <el-input v-model="formData.inRemark" type="textarea" placeholder="请输入备注" />
    </el-form-item>

    <el-form-item label="维修说明" prop="inRemark" v-if="oper == 'fix'">
      <el-input
        v-model="formData.inRemark"
        type="textarea"
        placeholder="请输入维修说明（原因，维修人等信息）"
      />
    </el-form-item>

    <el-form-item label="报废说明" prop="inRemark" v-if="oper == 'scrap'">
      <el-input
        v-model="formData.inRemark"
        type="textarea"
        placeholder="请输入报废说明（原因等信息）"
      />
    </el-form-item>
  </el-form>

  <!-- 用户选择弹窗 -->
  <UserSelectForm
    ref="userSelectFormRef"
    isInitGet
    notSuccessMessage
    @confirm="handleUserSelectConfirm"
  />
</template>
<script setup lang="ts">
import { AssetsFixedApi, AssetsFixedVO } from '@/api/school/assets/fixed'
import { AssetsFlowApi } from '@/api/school/assets/flow'
import { UserVO } from '@/api/system/user'
import { propTypes } from '@/utils/propTypes'
const route = useRoute()

/** 固定资产 表单 */
defineOptions({ name: 'AssetsFixedForm' })
const attrs = useAttrs()
/** 接收审批页面传递的参数 */
const props = defineProps({
  id: propTypes.number.def(undefined),
  disabled: propTypes.bool.def(false),
  operStr: propTypes.string.def('')
})

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  assetCode: undefined,
  catetoryId: undefined,
  name: undefined,
  inRemark: undefined,
  userIds: undefined,
  price: undefined, //维修费用
  oper: '' //操作类型
})
const formRules = reactive({
  name: [{ required: true, message: '物资名称不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '维修费用不能为空', trigger: 'blur' }],
  inRemark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
  userIds: [{ required: true, message: '领用人不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const selectedUsers = ref<UserVO[]>([])
const userSelectFormRef = ref()
const oper: string = computed(() => props.operStr || attrs.oper)
/** 处理用户选择确认 */
const handleUserSelectConfirm = (_, users: UserVO[]) => {
  selectedUsers.value = users || []
}

/** 打开人员选择 */
const openUserSelect = () => {
  userSelectFormRef.value.open(0, selectedUsers.value)
}

/** 移除人员 */
const handleRemoveUser = (user: UserVO) => {
  selectedUsers.value = selectedUsers.value.filter((userItem: any) => userItem.id !== user.id)
}

//窗口标题
const operMap = {
  borrow: '物资领用',
  returns: '归还物资',
  fix: '物资报修',
  scrap: '物资报废',
  reputin: '重新入库'
}

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  // dialogTitle.value = operMap[oper] || '未知操作'
  resetForm()
  // 设置数据
  formLoading.value = true
  try {
    formData.value = attrs.oper
      ? await AssetsFlowApi.getAssetsFlow(props.id)
      : await AssetsFixedApi.getAssetsFixed(props.id)
    formData.value.oper = props.operStr
    // formData.value.oper = 'fix'

    //清空人员选择器
    // formData.value.userIds = []
  } finally {
    formLoading.value = false
  }
}

watch(
  () => {
    return {
      formData: formData.value,
      userList: userSelectFormRef.value?.userList
    }
  },
  ({ formData, userList }: any) => {
    if (formData?.userIds?.length && userList?.length) {
      // 设置选中人员
      selectedUsers.value = userList.filter((userItem: any) =>
        formData.userIds.includes(userItem.id)
      )
    }
  },
  {
    deep: true
  }
)

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  //赋值领用人
  const userIds: any = selectedUsers.value?.map((user: any) => user.id)
  formData.value.userIds = userIds

  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AssetsFixedVO

    await AssetsFixedApi.operAssetsFixed(data)
    message.success(t('common.updateSuccess'))

    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    assetCode: undefined,
    catetoryId: undefined,
    name: undefined,
    inRemark: undefined,
    userIds: undefined,
    price: undefined, //维修费用
    oper: ''
  }
  formRef.value?.resetFields()
}
watch(
  () => props.id,
  (val) => {
    if (val) {
      open()
    }
  },
  {
    immediate: true
  }
)
defineExpose({ open, submitForm }) // 提供 open 方法，用于打开弹窗
</script>

<style scoped>
:deep(.blue-divider .el-divider__text) {
  color: rgb(64, 158, 255);
}
</style>
